<template>
  <div>
    <el-dialog
      title="选择分类"
      :visible.sync="messageShow"
      width="20%"
      :before-close="handleClose"
      append-to-body
    >
      <span class="tree-area">
        <el-tree
          ref="tree"
          :data="searchType"
          show-checkbox
          node-key="recNo"
          :default-checked-keys="keysOnCancel"
          v-if="messageShow"
          :default-expanded-keys="expandRowKey"
          label="label"
        >
        </el-tree>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleOK">确 定</el-button>
        <el-button @click="hide">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getClass } from "@/api/search/complex.js"

export default {
  props: ["messageShow", "options"],
  data () {
    return {
      selectedKeys: [],
      keysOnCancel: [],
      selected: [],
      confirmed: [],
      expandRowKey: [0],
      searchType: []
    };
  },
  methods: {
    hide () {
      this.$emit("update:messageShow", false);
      this.selected = [...this.confirmed];
    },
    handleClose () {
      this.hide();
    },
    handleOK () {
      const selectedNodes = this.$refs.tree.getCheckedNodes();
      //筛选返回数据中isLast为0的检索类型,并发送给Form
      const filteredNodes = selectedNodes.filter((item) => item.isLast == 0);
      if (filteredNodes.length > 0) {
        this.selected = filteredNodes;
        this.confirmed = filteredNodes;
        this.selectedKeys = filteredNodes.map((item) => item.recNo);
        this.keysOnCancel = this.selectedKeys;
        if (this.options) {
          this.$emit("update:options", filteredNodes);
        }
        this.$bus.$emit("options", filteredNodes);
        this.hide();
      } else {
        this.$message({
          message: "请选择至少一个分类",
          type: "warning",
        });
      }
    },
  },
  created () {
    if (this.options) {
      this.selected = this.options;
      this.confirmed = this.options;
      this.selectedKeys = this.options.map((item) => item.recNo);
      this.keysOnCancel = this.selectedKeys;
    }
  },
  mounted () {
    getClass().then((res) => {
      this.searchType = res.rows;
      this.expandRowKey = [res.rows[0].recNo];
    })
  },
  watch: {
    messageShow () {
      this.keysOnCancel = [...this.selectedKeys];
    },
  },
};
</script>

<style scoped>
.tree-area {
  display: block;
  min-height: 200px;
  border: 2px solid rgb(235,238,245);
  margin: 0 auto;
  padding: 20px;
}
.el-tree {
  overflow: hidden;
}
</style>
